package utils
{
	import core.actor.core.ActorView;
	
	public class ArrayUtil
	{
		public static var showCharList:Array = [];
		public static var length:int = 0;//屏幕上显示出来的人数
		
		/**
		 * 排序 
		 * @param character
		 * @param isInit
		 * 
		 */
		public static function updateCharacter(actor:ActorView,isInit:Boolean=false):void{
			if(actor.isMove()||isInit){
				deleteArray(actor);
				var index:int = bsearch(showCharList,actor.y,0,showCharList.length-1);
				insertArray(actor,index);
			}
			length =  showCharList.length;
		} 
		
		/**
		 * 
		 * @param sortArray 从小到大排序的数组
		 * @param value
		 * @param left
		 * @param right
		 * @return 要插入的数组下标
		 * 
		 */
		private static function bsearch(sortArray:Array,value:int,left:int,right:int):int{
			if(sortArray.length==0){
				return 0;
			}
			if(right - left <=1){
				if(value>sortArray[right].y||value==sortArray[right].y){
					return right+1;
				}else if(value>sortArray[left].y||value==sortArray[left].y){
					return left+1;
				}
				return left;
			}
			
			var center:int = (left+right)/2;
			if(sortArray[center].y<value){//数组的中间值 小于 当前值 
				return bsearch(sortArray,value,center,right);
			}else if(sortArray[center].y>value){//数组的中间值 大于 当前值 
				return bsearch(sortArray,value,left,center);
			}else{
				return center+1;
			}
		} 
		
		/**
		 * 
		 * @param targetArray 要排序的数组
		 * @param target 要插入的对象
		 * @param index 要插入的下标位置
		 * 
		 */
		private static function insertArray(actor:ActorView,index:int):void{
			 var size:int = showCharList.length;
			 if(index>=size){
			 	showCharList.push(actor);
			 }else{
			 	var tempArray:Array = showCharList.concat();//生成新的数组
			 	showCharList[index] = actor;
			 	for(var i:int=index;i<size;i++){
					showCharList[i+1] = tempArray[i];	 		
			 	}
			 }
		}
		
		
		/**
		 * 从列表中删除
		 * @param targetArray
		 * @param cid
		 * 
		 */
		public static function deleteArray(actor:ActorView):void{
			length = showCharList.length;
			for(var i:int=0;i<length;i++){
				if(showCharList[i].cid==actor.cid){
					showCharList.splice(i,1);
					length = showCharList.length;
					return;
				}
			}
		}
		
		public static function toString():String{
			var str:String = "\n size("+showCharList.length+")";
			
			for(var i:int=0;i<showCharList.length;i++){
				str+="\n name("+showCharList[i].cid+"=("+showCharList[i].boneLayer.x + "," +showCharList[i].boneLayer.y+"))";
			}
			
			return str;
			
			/*var str:String="size("+showCharList.length+")<br>";
			for(var i:int=0;i<showCharList.length;i++){
				str+="name("+showCharList[i].cid+"="+showCharList[i].y+")<br>";
			}
			return str;*/
		}
	}
}